<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="验货单号" prop="checkNumber">
        <el-input
          v-model="queryParams.checkNumber"
          placeholder="请输入验货单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="验货日期" prop="checkDate">
         <el-date-picker
          v-model="daterangeCheckDate"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="验货单状态" prop="checkStatus">
        <el-select v-model="queryParams.checkStatus" placeholder="请选择验货单状态" clearable size="small">
          <el-option
            v-for="dict in checkStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="验货类型" prop="checkType">
        <el-select v-model="queryParams.checkType" placeholder="请选择验货类型" clearable size="small">
          <el-option
            v-for="dict in checkTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['supplier:checkProduct:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['supplier:checkProduct:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['supplier:checkProduct:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['supplier:checkProduct:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkProductList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="30" align="center" />
      <el-table-column label="ID" align="center" prop="checkIdPk" width="50" />
      <el-table-column label="验货单号" align="center" prop="checkNumber" min-width="120px"/>
      <el-table-column label="验货日期" align="center" prop="checkDate" width="170px">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span>{{ parseTime(scope.row.checkDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="验货单状态" align="center" prop="checkStatus" :formatter="checkStatusFormat" />
      <el-table-column label="验货类型" align="center" prop="checkType" :formatter="checkTypeFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['supplier:checkProduct:edit']"
            v-show="scope.row.checkStatus === 0"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['supplier:checkProduct:remove']"
           v-show="scope.row.checkStatus === 0"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleView(scope.row)"
            v-hasPermi="['supplier:checkProduct:view']"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改验货对话框 -->
    <el-dialog :title="title" :visible.sync="open" :fullscreen="true" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="验货单号" prop="checkNumber">
          <el-input v-model="form.checkNumber" placeholder="请输入验货单号" :disabled="true"/>
        </el-form-item>
        <el-form-item label="验货日期" prop="checkDate" >
          <el-date-picker clearable size="small" :disabled="showView"
            v-model="form.checkDate"
            type="datetime" format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择验货日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="验货单状态" prop="checkStatus" >
          <el-select v-model="form.checkStatus" placeholder="请选择验货单状态" :disabled="showView">
            <el-option
              v-for="dict in checkStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="验货类型" prop="checkType" >
          <el-select v-model="form.checkType" placeholder="请选择验货类型" :disabled="showView">
            <el-option
              v-for="dict in checkTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="进货总金额" prop="totalAmount">
          {{ this.form.totalAmount }}（元）
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="showView" />
        </el-form-item>
        <el-divider content-position="center">验货明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddTbCheckProductDetail" v-show="!showView">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddTbPurchase" v-show="!showView">添加采购单</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteTbCheckProductDetail" v-show="!showView">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="tbCheckProductDetailList" :row-class-name="rowTbCheckProductDetailIndex" @selection-change="handleTbCheckProductDetailSelectionChange" ref="tbCheckProductDetail">
          <el-table-column type="selection" width="30" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="商品条码起始" prop="barcode" min-width="100px">
            <template slot-scope="scope">
              <el-input v-model="scope.row.barcode" placeholder="请输入商品条码起始"  :disabled="showView"  maxlength="16" show-word-limit @blur="handleBarcode(scope.row)" @change="handleBarcode(scope.row)"/>
            </template>
          </el-table-column>
          <el-table-column label="商品条码截止" prop="barcodeEnd">
          </el-table-column>
          <el-table-column label="商品名称" prop="productName" min-width="80px">
          </el-table-column>
          <el-table-column label="是否包装类型" prop="isPack" :formatter="isPackFormat"/>
          <el-table-column label="规格" prop="itemName" min-width="50px">
          </el-table-column>
          <el-table-column label="计量单位" prop="measurement" min-width="50px" :formatter="measurementFormat">
          </el-table-column>
          <el-table-column label="品牌名称" prop="brandDesc"  min-width="50px">
          </el-table-column>
          <el-table-column label="供应商名称" prop="supplierName">
          </el-table-column>
          <el-table-column label="验货数量" prop="qty"  min-width="70px">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.qty" placeholder="验货数量" size="small" :disabled="showView" :step="1" :min="0" @change="handleBarcode(scope.row);handleQtyChange(scope.row)"/>
            </template>
          </el-table-column>
          <el-table-column label="参考单价" prop="referencePrice" class-name="text-danger" min-width="50px">
          </el-table-column>
         
          <el-table-column label="供货价" align="center" prop="price" min-width="100px">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.price"
                  controls-position="right"
                  placeholder="请输入供货价"
                  @change="handleQtyChange(scope.row)"
                  :precision="2"
                  :step="0.01"
                  size="mini"
                  step-strictly
                  :disabled="showView"
                />
              </template>
          </el-table-column>

          
          <el-table-column label="进货总金额" prop="amount" />
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm(0)" v-show="!showView">保 存</el-button>
        <el-button type="success" @click="submitForm(1)" v-show="!showView">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--选中商品组件-->
    <product-dialog
      :product-props.sync="productData"
      :handle-select="handleSelectProduct"
      ref="productParams"
    />

    <!--采购明细-->
    <purchase-dialog ref="purchaseParams" 
      :purchase-props.sync="purchaseData"
      :handle-select="handleSelectPurchase" 
      :radiobox="false"/>

  </div>
</template>

<script>
import { listCheckProduct, getCheckProduct, delCheckProduct, addCheckProduct, updateCheckProduct, exportCheckProduct,generateNumber,checkBarcode } from "@/api/supplier/checkProduct";
import productDialog from "@/views/supplier/product/dialog";
import purchaseDialog from "@/views/supplier/purchase/dialog";
export default {
  name: "CheckProduct",
  components: {
    productDialog,
    purchaseDialog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTbCheckProductDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 查看标识
      showView: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 验货表格数据
      checkProductList: [],
      // 验货日期时间范围
      daterangeCheckDate: [],
      // 验货明细表格数据
      tbCheckProductDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 验货单状态字典
      checkStatusOptions: [],
      // 验货类型字典
      checkTypeOptions: [],
       // 计量单位字典
      measurementOptions: [],
       typeOptions:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        checkNumber: null,
        checkDate: null,
        checkStatus: null,
        checkType: null,
        orderByColumn: "checkIdPk",
        isAsc: "desc"
      },
      productData: {
        open: false,
        currentQtyShow: true,
        productList: [],
        //隐藏单价
        priceShow: true,
      },
      purchaseData: {
        open: false,
        purchaseList: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("bus_check_status").then(response => {
      this.checkStatusOptions = response.data;
    });
    this.getDicts("bus_check_type").then(response => {
      this.checkTypeOptions = response.data;
    });
    this.getDicts("bus_measurement").then(response => {
      this.measurementOptions = response.data;
    });
    this.getDicts("sys_yes_no").then(response => {
      this.typeOptions = response.data;
    });
  },
  methods: {
    /** 查询验货列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCheckDate && '' != this.daterangeCheckDate) {
        this.queryParams.params["beginCheckDate"] = this.daterangeCheckDate[0];
        this.queryParams.params["endCheckDate"] = this.daterangeCheckDate[1];
      }

      listCheckProduct(this.queryParams).then(response => {
        this.checkProductList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 验货单状态字典翻译
    checkStatusFormat(row, column) {
      return this.selectDictLabel(this.checkStatusOptions, row.checkStatus);
    },
    // 验货类型字典翻译
    checkTypeFormat(row, column) {
      return this.selectDictLabel(this.checkTypeOptions, row.checkType);
    },
    // 计量单位字典翻译
    measurementFormat(row, column) {
      return this.selectDictLabel(this.measurementOptions, row.measurement);
    },
    isPackFormat(row,column){
      return this.selectDictLabel(this.typeOptions, row.isPack);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        checkIdPk: null,
        checkNumber: null,
        checkDate: null,
        checkStatus: null,
        checkType: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.tbCheckProductDetailList = [];
      this.daterangeCheckDate = [];
      this.$refs.productParams.queryParams.ids =[];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCheckDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.checkIdPk)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleSelectProduct(data) {
      data.forEach((item) => {
        this.tbCheckProductDetailList.push(item);
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      generateNumber().then((response) => {
        this.reset();
        this.form.checkNumber = response.msg;
        this.form.checkStatus = 0;
        this.form.checkType=0;
        this.form.checkDate=new Date();
        this.showView=false;
        this.title = "添加验货";
        this.open = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.showView=false;
      const checkIdPk = row.checkIdPk || this.ids
      getCheckProduct(checkIdPk).then(response => {

        this.form = response.data;
        if(this.form.checkStatus!=0){
          this.msgError("已提交数据，不能修改!");
          return;
        }
        
        this.tbCheckProductDetailList = response.data.tbCheckProductDetailList;
        this.open = true;
        this.title = "修改验货";
      });
    },
    handleView(row){
      this.reset();
      const checkIdPk = row.checkIdPk || this.ids
      getCheckProduct(checkIdPk).then(response => {
        this.form = response.data;
        this.showView=true;
        this.tbCheckProductDetailList = response.data.tbCheckProductDetailList;
        this.open = true;
        this.title = "查看验货";
      });
    },

    handleBarcode(row){

        if(row.qty>0 && row.barcode !=null ){
            
            row.barcodeEnd=parseInt(row.barcode)+parseInt(row.qty)-1;
            checkBarcode(row).then(response => {
              this.msgSuccess(response.msg)
            });
        }
       
    },
    /** 提交按钮 */
    submitForm(status) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.checkStatus = status;
 
          this.form.tbCheckProductDetailList = this.tbCheckProductDetailList;
          if (this.form.checkIdPk != null) {
            updateCheckProduct(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCheckProduct(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const checkIdPks = row.checkIdPk || this.ids;
 
     
      this.$confirm('是否确认删除验货编号为"' + checkIdPks + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delCheckProduct(checkIdPks);
        }).then((ret) => {
          if(ret.data!=null && ret.data==-1){
            this.msgError("包含已提交数据，不能删除!");
          }
          else {
            this.getList();
            this.msgSuccess("删除成功");

          }
        });
    },
	/** 验货明细序号 */
    rowTbCheckProductDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 验货明细添加按钮操作 */
    handleAddTbCheckProductDetail() {
      this.$refs.productParams.open = true;
      this.$refs.productParams.getProductList();
    },
    handleAddTbPurchase(){
      
      this.$refs.purchaseParams.open = true;
      this.$refs.purchaseParams.getPurchaseList();

    },
    /** 验货明细删除按钮操作 */
    handleDeleteTbCheckProductDetail() {
      if (this.checkedTbCheckProductDetail.length == 0) {
        this.$alert("请先选择要删除的入库明细数据", "提示", {
          confirmButtonText: "确定",
        });
      } else {
      
        this.checkedTbCheckProductDetail.forEach((item) => {
          for (let i = 0; i < this.tbCheckProductDetailList.length; i++) {
            if (this.tbCheckProductDetailList[i].index == item.index) {
             
              this.tbCheckProductDetailList.splice(i, 1);
              var indexProduct = this.$refs.productParams.queryParams.ids.findIndex((value)=>value==item.priceId);
              if(indexProduct==0){ //判断要删除的ID是否在已经勾选的范围内
                this.$refs.productParams.queryParams.ids.splice(i, 1);
              }
              var indexPurchase = this.$refs.purchaseParams.queryParams.ids.findIndex((value)=>value==item.priceId);
              if(indexPurchase==0){
                 this.$refs.purchaseParams.queryParams.ids.splice(i, 1);
              }
              break;
            }
          }
        });

        this.checkedTbCheckProductDetail = [];
      }
    },
    /** 单选框选中数据 */
    handleTbCheckProductDetailSelectionChange(selection) {
      
        this.checkedTbCheckProductDetail = selection;
  
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有验货数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportCheckProduct(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    handleQtyChange(row) {
      // row.amount= row.marketPrice * row.qty
      row.amount = this.$math.multiply(row.price, row.qty).toFixed(2);

      let amount = 0;

      this.tbCheckProductDetailList.map((item) => {
        if (item.amount != null && item.amount != 0) {
          amount = this.$math.add(amount, item.amount);
        }
      });

      this.form.totalAmount = amount.toFixed(2);
    },
    handleSelectPurchase(data) {
      data.forEach((item) => {
        this.tbCheckProductDetailList.push(item);
      });
    },
  }
};
</script>
